﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace eLearning.DosenView
{
    public partial class ListMahasiswaPage : PhoneApplicationPage
    {

        // Handle loading animation in this page
        public bool ShowProgress
        {
            get { return (bool)GetValue(ShowProgressProperty); }
            set { SetValue(ShowProgressProperty, value); }
        }
        public static readonly DependencyProperty ShowProgressProperty = DependencyProperty.Register("ShowProgress", typeof(bool), typeof(ListMahasiswaPage), new PropertyMetadata(false));

        public ListMahasiswaPage()
        {
            InitializeComponent();
            PivotMahasiswa.SelectedIndex = 1;
        }

        private void LoadRegisteredMahasiswa()
        {            
            WebClient webClient = new WebClient();

            string url = string.Format("{0}&{1}", Config.Instance.MHS_SERVICE_URL() + Config.REG_VIEW_APPROVED_KEY, Guid.NewGuid().ToString());
            Uri uri = new Uri(url, UriKind.Absolute);
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(listRegistered_DownloadStringCompleted);
            webClient.AllowReadStreamBuffering = true;
            webClient.DownloadStringAsync(uri);
        }

        private void listRegistered_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            listMahasiswa.Items.Clear();
            if (e.Error != null)
                return;

            try
            {
                MahasiswaList list = JsonConvert.DeserializeObject<MahasiswaList>(e.Result);
                if (list.Count > 0)
                {
                    foreach (Mahasiswa mhs in list)
                    {
                        Mahasiswa mahasiswa = mhs;
                        mahasiswa.Status = Mahasiswa.STATUS.NONE;
                        listMahasiswa.Items.Add(mahasiswa);
                    }
                    //listMahasiswa.ItemsSource = list;
                }
                else
                {
                    listMahasiswa.ItemsSource = null;
                }
                ShowProgress = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                ShowProgress = false;
            }
        }
             
        private void LoadNotApprovedMahasiswa()
        {
            ShowProgress = true;
            WebClient webClient = new WebClient();

            string url = string.Format("{0}&{1}", Config.Instance.MHS_SERVICE_URL() + Config.REG_VIEW_NOT_APPROVED_KEY, Guid.NewGuid().ToString());
            Uri uri = new Uri(url, UriKind.Absolute);
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(listNotApproved_DownloadStringCompleted);
            webClient.AllowReadStreamBuffering = true;
            webClient.DownloadStringAsync(uri);
        }

        private void listNotApproved_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            listNotApproved.Items.Clear();
            if (e.Error != null)            
                return;
            
            try
            {
                MahasiswaList list = JsonConvert.DeserializeObject<MahasiswaList>(e.Result);
                if (list.Count > 0)
                {
                    foreach (Mahasiswa mhs in list)
                    {
                        Mahasiswa mahasiswa = mhs;
                        mahasiswa.Status = Mahasiswa.STATUS.REGISTER;
                        listNotApproved.Items.Add(mahasiswa);
                    }
                    //listMahasiswa.ItemsSource = list;
                }
                else
                {
                    listNotApproved.ItemsSource = null;
                }
                
                ShowProgress = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                ShowProgress = false;
            } 
        }
        
        private void ApproveAllPendaftaran()
        {
            ShowProgress = true;
            WebClient webClient = new WebClient();
            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(approvePendaftaran_UploadStringCompleted);
            webClient.UploadStringAsync(new Uri(Config.Instance.DOSEN_SERVICE_URL() + Config.REG_APPROVE_ALL_KEY, UriKind.Absolute), "");
        }

        private void approvePendaftaran_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled && e.Error != null)
                {
                    return;
                }
                MessageBox.Show("Message : " + e.Result);
                if (e.Result.Contains("approved"))
                    RefreshPage();
                ShowProgress = false;
            }
            catch (WebException ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
                ShowProgress = false;
            }
        }

        private void listMahasiswa_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                // get RSS item from ListBox and store in class var. Store page to navigate to in class var.
                Mahasiswa mhs = (Mahasiswa)e.AddedItems[0];

                // reset selection of ListBox
                ((ListBox)sender).SelectedIndex = -1;
                
                // change  page navigation 
                Utility.GotoPage(this, "/View/Dosen/MahasiswaDetailPage.xaml");
                PhoneApplicationService.Current.State[Config.MHS] = mhs;
            }
        }
        
        // Navigate to this page
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            ShowProgress = true;
            RefreshPage();
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            if(e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
                Utility.GotoPage(this, "/View/Dosen/DashboardPage.xaml");
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            RefreshPage();
        }

        private void RefreshPage()
        {
            LoadRegisteredMahasiswa();
            LoadNotApprovedMahasiswa();
            ManageButton();
        }

        private void buttonApproveAll_Click(object sender, EventArgs e)
        {
            ApproveAllPendaftaran();
            ManageButton();
        }

        private void PivotMahasiswa_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ManageButton();
        }

        private void ManageButton()
        {
            if (PivotMahasiswa.SelectedIndex == 0 || listNotApproved.Items.Count <= 0)
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;
            else
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = true;
        }

    }
}